var exp = require('express')
const { item, User, img, car } = require('../lib/mongodb')
var fs = require('fs')
var multer = require('multer')
var app = exp.Router()
app.get('/save', (req, res) => {
    item(req.query.obj).save()
})
app.get('/upsave', (req, res) => {
    item.updateOne({
        _id: req.query.obj.id
    }, { pay: req.query.obj.pay }, (err) => {

    })
})
app.get('/del', (req, res) => {
    item.deleteOne({
        _id: req.query.id
    }, (err) => {
        res.send('删除成功')
    })
})
app.get('/upData', (req, res) => {
    if (req.query.se) {
        User.updateOne({
            _id: req.cookies.phone
        }, { username: req.query.se }, (err) => {
            if (!err) {
                res.cookie('user', req.query.se)
                res.send('修改成功')

            }
        })
    }

})
app.get('/uppassword', (req, res) => {
    User.findOne({
        _id: req.cookies.phone
    }, (err, data) => {
        if (data.psw == req.query.oldpassword) {
            User.updateOne({
                _id: req.cookies.phone
            }, { psw: req.query.newpassword }, err => {
                res.send('修改成功')
            })
        } else {
            res.send('原来密码错误或未填')
        }
    })
})
var storage = multer.diskStorage({
    destination: 'www/userimg',
    filename: function (req, file, callback) {
        var filename = req.cookies.phone + '.' + file.mimetype.split('/')[1]
        req.body.img = filename
        callback(null, filename)
    }
})
var upload = multer({ storage })
app.post('/upload', upload.single('photo'), (req, res) => {
    img.findOne({
        iduser: req.cookies.phone
    }, (err, data) => {
        if (data) {
            img.updateOne({
                iduser: req.cookies.phone
            }, {
                imgurl: `userimg/${req.body.img}`
            }, (err) => {

            })
        } else {
            img({
                imgurl: `userimg/${req.body.img}`,
                iduser: req.cookies.phone
            }).save()
        }
    })
    res.send('上传成功')
})
app.get('/savecar', (req, res) => {
    car.findOne({
        ids: req.query.obj.ids
    }, (err, data) => {
        if (data) {

        } else {
            car(req.query.obj).save()
            res.send('保存成功')
        }
    })

})
app.get('/gouwuche', (req, res) => {
    car.find((err, data) => {
        res.send(data)
    })
})
app.get('/delcar', (req, res) => {
    car.deleteOne({
        ids: req.query.id
    }, (err, data) => {
        res.send('取消收藏')
    })
})
app.get('/del1', (req, res) => {
    console.log(req.query.es);
    car.deleteMany({
        $or: req.query.es
    }, (err) => {
        res.send('删除成功')
    })
})
module.exports = app